{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "35177005-196a-48b3-bf92-fa37d84693f4",
   "metadata": {},
   "source": [
    "# Outlook API Credential Guide"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "7bcad9ee-cd11-4b12-834d-9f1ddcefb190",
   "metadata": {},
   "source": [
    "Extract Outlook Emails via Microsoft Graph API\n",
    "\n",
    "1. Register Your App on Azure Portal\n",
    "\n",
    "   Go to Azure Portal > Azure Active Directory > App registrations\n",
    "\n",
    "   Click “New registration”\n",
    "\n",
    "   Choose Mobole/Desktop app\n",
    "   \n",
    "   After creation, note the Application (client) ID\n",
    "\n",
    "2. API Permissions\n",
    "\n",
    "   Go to API permissions tab\n",
    "\n",
    "   Click Add permission > Microsoft Graph > Delegated\n",
    "\n",
    "   Choose: Mail.Read\n",
    "\n",
    "   Click Grant admin consent\n",
    "\n",
    "3. Allow public client flows\n",
    "\n",
    "   Navigate to: Azure Active Directory > App registrations > Your App\n",
    "\n",
    "   Go to Authentication tab\n",
    "\n",
    "   Under \"Advanced settings\" → \"Allow public client flows\", set to \"Yes\"\n",
    "\n",
    "   Save changes"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "bc86bec0-bda8-4e9e-9c85-423179a99981",
   "metadata": {},
   "outputs": [],
   "source": [
    "!pip install msal requests"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "4270e52e-378c-4127-bd52-1d082e9834e0",
   "metadata": {},
   "outputs": [],
   "source": [
    "from msal import PublicClientApplication\n",
    "import os\n",
    "from dotenv import load_dotenv\n",
    "import requests"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "5ff68e06-3cfb-48ae-9dad-fa431d0d548a",
   "metadata": {},
   "outputs": [],
   "source": [
    "load_dotenv()\n",
    "\n",
    "CLIENT_ID = os.getenv(\"AZURE_CLIENT_ID\")\n",
    "AUTHORITY = \"https://login.microsoftonline.com/common\" \n",
    "SCOPES = [\"Mail.Read\"]\n",
    "\n",
    "app = PublicClientApplication(CLIENT_ID, authority=AUTHORITY)\n",
    "\n",
    "flow = app.initiate_device_flow(scopes=SCOPES)\n",
    "print(\"Go to:\", flow[\"verification_uri\"])\n",
    "print(\"Enter code:\", flow[\"user_code\"])\n",
    "\n",
    "result = app.acquire_token_by_device_flow(flow)\n",
    "\n",
    "if \"access_token\" not in result:\n",
    "    raise Exception(\"Failed to authenticate:\", result)\n",
    "\n",
    "access_token = result[\"access_token\"]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "9c7f97da-68cc-4923-b280-1ddf7e5b7aa3",
   "metadata": {},
   "outputs": [],
   "source": [
    "print(\"Granted scopes:\", result.get(\"scope\"))\n",
    "\n",
    "headers = {\n",
    "    \"Authorization\": f\"Bearer {access_token}\",\n",
    "    \"Prefer\": \"outlook.body-content-type='text'\"\n",
    "}\n",
    "\n",
    "query = (\n",
    "    \"https://graph.microsoft.com/v1.0/me/messages\"\n",
    "    \"?$top=1\"\n",
    "    \"&$select=id,subject,receivedDateTime,body\"\n",
    ")\n",
    "\n",
    "all_emails = []\n",
    "\n",
    "while query:\n",
    "    response = requests.get(query, headers=headers)\n",
    "\n",
    "    if not response.ok:\n",
    "        print(response.text)\n",
    "        print(f\"❌ HTTP {response.status_code}: {response.text}\")\n",
    "        break\n",
    "\n",
    "    try:\n",
    "        res = response.json()\n",
    "    except ValueError:\n",
    "        print(\"❌ Invalid JSON:\", response.text)\n",
    "        break\n",
    "\n",
    "    for msg in res.get(\"value\", []):\n",
    "        all_emails.append({\n",
    "            \"id\": msg.get(\"id\"),\n",
    "            \"subject\": msg.get(\"subject\", \"\"),\n",
    "            \"body\": msg.get(\"body\", {}).get(\"content\", \"\"),\n",
    "            \"date\": msg.get(\"receivedDateTime\", \"\")\n",
    "        })\n",
    "\n",
    "    query = res.get(\"@odata.nextLink\")\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "e29493b6-0a9e-4106-93c9-e58ff6aa0f97",
   "metadata": {},
   "outputs": [],
   "source": [
    "all_emails"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.11.13"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
